/**
 * Created by zhang on 4/28/2017.
 */
var fs = require('fs');
var path = require('path');

/**
 * 遍历目录算法
 *
 * 1. 深度优先
 * 2. 先序遍历
 *
 */

/**
 * 同步遍历
 */
function travelSync(dir, callback) {
    fs.readdirSync(path.normalize(dir)).forEach(function (file) {

        var filePath = path.join(dir, file);

        if (fs.statSync(filePath).isDirectory()){
            travelSync(filePath, callback);
        }else {
            callback(filePath);
        }

    });
}

travelSync(path.join('c:', 'Users', 'zhang', 'Desktop'), function (filePath) {
    console.log(filePath);
});

/**
 * 异步遍历
 */
function travel(dir, callback, finish) {
    fs.readdir(dir, function (err, files){
        (function next(i){
            if (i < files.length){
                var filePath = path.join(dir, files[i]);

                fs.stat(filePath, function (err, stats) {
                    if (stats.isDirectory()){
                        travel(filePath, callback, function () {
                            next( i + 1 );
                        })
                    }else{
                        callback(filePath, function () {
                            next( i + 1 );
                        });
                    }
                });

            }else {
                finish && finish();
            }
        }(0));
    });
}

var filePaths = [];

travel(path.join('C:', 'Users', 'zhang', 'Desktop'), function (filePath) {
    filePaths.push(filePath);
});

var j;

for (j = 0; j < filePaths.length; j++){
    console.log(filePaths[j]);
}

























